package org.uim.cricket.analyzer.analyze.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.uim.cricket.analyzer.analyze.Alogger;
import org.uim.cricket.analyzer.analyze.InningMappable;
import org.uim.cricket.entities.aggr.SingleInning;
import org.uim.cricket.entities.match.CricketMatch;
import org.uim.cricket.util.CricketFunctions;

/**
 * Creates a inning list which corresponding to each team played.
 * 
 * @version 1.0
 * @author Isuru Madushanka
 *
 */
public class InningsMapper implements InningMappable  {

	private CricketFunctions cf = new CricketFunctions();
	
	@Override
	public Map<String, List<SingleInning>> getInningMap(CricketMatch match) {
		Map<String, List<SingleInning>> result = new HashMap<String, List<SingleInning>>();
		
		SingleInning[] innings = match.getInnings();
		if (innings == null) {
			result.put(match.getTeam1(), null);
			result.put(match.getTeam2(), null);
			Alogger.debug("No innings are found for the match + " + match.getId().getPrefix() + "#" + match.getId().getInternationalID());
			return result;
		}
		
		Alogger.debug("iterating through innings...");
		for (int i=0; i<innings.length; i++) {
			SingleInning inn = innings[i];
			if (inn == null) {
				Alogger.debug("Inning " + (i+1) + " is empty!");
				continue;
			}
			
			if (inn.getBowledTeam() == null || inn.getBowledTeam().length() == 0) {
				inn.setBowledTeam(cf.getComplementTeam(match.getTeam1(), match.getTeam2(), inn.getBattedTeam()));
			}
			
			Alogger.info("Inning #"+(i+1)+": [" + inn.getBattedTeam() + " batted], [" + inn.getBowledTeam() + " bowled].");
			List<SingleInning> innList = result.get(inn.getBattedTeam());
			if (innList == null) {
				innList = new ArrayList<SingleInning>();
				innList.add(inn);
				result.put(inn.getBattedTeam(), innList);
			} else {
				innList.add(inn);
			}
			
		}
		Alogger.debug("Completed iterating.");
		
		return result;
	}

}
